import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import update from 'react-addons-update';

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    ...PageConst,
    position: {},
    files: [],
    gallery: false,
    urls: [],
    galleryIndex:''
  },

  onHideFiles: function () {
    this.data.gallery = update(this.data.gallery, {$set: false});
    this.updateComponent();
  },

  onShowFiles: function (index) {
    this.data.gallery = update(this.data.gallery, {$set: true});
    this.data.galleryIndex = update(this.data.galleryIndex, {$set: index});

    this.data.urls = update(this.data.urls, {$set: []});
    this.data.urls = update(this.data.urls, {
      $apply: (urls)=> {
        return this.data.files.map((v, i)=> {
          return urls.concat(v.url);
        })
      }
    })

    console.log(this.data.urls)
    this.updateComponent();

  },

  onAddFiles: function (obj) {

    this.data.files = update(this.data.files, {
      $apply: (files)=> {
        return files.concat(update(obj, {$merge: {url: obj.data}}));
      }
    })
    this.updateComponent();
  },

  onSetPosition: function (obj) {
    this.data.position = update(this.data.position, {$set: obj});
    this.updateComponent();
  },

  onFetch: function (params, cb) {
    let t = this;
    t.updateComponent();
    cb && cb(t.data);
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
